package com.example.algorithm.stacklist;

import java.util.Stack;

/**
 * @author : zhy
 * @since : 2022/7/27
 * 删除字符串中的所有相邻重复项
 */
public class DeleteReplace {

    public String removeDuplicates(String s) {
        char[] array = s.toCharArray();
        int len=array.length;
        if(len==1){
            return String.valueOf(array[0]);
        }
        Stack<Character> stack=new Stack<>();
        Stack<Character> stack1=new Stack<>();
        stack.push(array[0]);
        for(int i=1;i<len;i++)
        {
            if(!stack.isEmpty()&&array[i]==stack.peek())
            {
                stack.pop();
            }else {
                stack.push(array[i]);
            }
        }
        StringBuilder builder = new StringBuilder();
        int size = stack.size();
        for(int i=0;i<size;i++)
        {
            stack1.push(stack.pop());
        }
        for(int i=0;i<size;i++)
        {
            builder.append(stack1.pop());
        }
        return builder.toString();
    }

    public static void main(String[] args) {
        DeleteReplace replace = new DeleteReplace();
        System.out.println(replace.removeDuplicates("abbbabaaa"));
    }


}
